import openpyxl
import os

# 设置文件路径
file_path = r"e:\Projects\program-py\LEARN-数据分析\CASE-dashboard_epidemic\香港各区疫情数据_20250322.xlsx"

def read_excel_fields_and_data():
    """读取Excel文件的字段和前20行数据"""
    try:
        # 加载工作簿
        workbook = openpyxl.load_workbook(file_path, data_only=True)
        
        # 获取所有工作表名称
        sheet_names = workbook.sheetnames
        print("=" * 80)
        print("Excel文件工作表信息")
        print("=" * 80)
        print(f"工作表数量: {len(sheet_names)}")
        print("工作表名称:")
        for i, name in enumerate(sheet_names, 1):
            print(f"  {i}. {name}")
        
        # 读取第一个工作表
        sheet = workbook.active
        print(f"\n当前读取工作表: {sheet.title}")
        print("=" * 80)
        
        # 读取所有数据
        data = []
        for row in sheet.iter_rows(values_only=True):
            data.append(row)
        
        if not data:
            print("文件中没有数据")
            return
        
        # 显示字段信息
        print("\n字段信息:")
        print("-" * 60)
        headers = data[0] if data else []
        for i, header in enumerate(headers, 1):
            print(f"字段{i:2d}: {header}")
        
        # 显示前20行数据
        print(f"\n前20行数据:")
        print("-" * 80)
        
        # 计算每列的最大宽度
        max_widths = []
        for col in range(len(headers)):
            max_width = max(
                len(str(headers[col])) if headers[col] is not None else 0,
                max(len(str(row[col])) if row[col] is not None else 0 for row in data[1:21])
            )
            max_widths.append(max(max_width, 12))  # 最小宽度为12
        
        # 打印表头
        header_str = ""
        for i, header in enumerate(headers):
            header_value = str(header) if header is not None else ""
            header_str += f"{header_value:<{max_widths[i]}}  "
        print(header_str)
        print("-" * 80)
        
        # 打印前20行数据（包括表头，所以实际是19行数据）
        rows_to_show = min(20, len(data))
        for i in range(1, rows_to_show):
            row = data[i]
            row_str = ""
            for j, cell in enumerate(row):
                cell_value = str(cell) if cell is not None else ""
                row_str += f"{cell_value:<{max_widths[j]}}  "
            print(row_str)
        
        # 显示数据统计
        print(f"\n数据统计:")
        print("-" * 40)
        print(f"总行数: {len(data)}")
        print(f"总列数: {len(headers)}")
        print(f"显示行数: {min(19, len(data)-1)}")
        
        workbook.close()
        
    except FileNotFoundError:
        print(f"错误: 找不到文件 {file_path}")
        print("请确认文件路径是否正确")
    except Exception as e:
        print(f"读取文件时出错: {e}")

def main():
    print("=" * 80)
    print("香港各区疫情数据分析")
    print("=" * 80)
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        print("当前目录中的文件:")
        for file in os.listdir('.'):
            if file.endswith(('.xlsx', '.xls')):
                print(f"  - {file}")
        return
    
    read_excel_fields_and_data()
    
    print("\n" + "=" * 80)
    print("分析完成!")

if __name__ == "__main__":
    main()